/***********************************************************************************************************************************
 * Name:	Template_AllDBs.sql
 * Author:	Frank Figearo (frank@sqlnerd.me)
 * Summary:	Template for a new query to step through all DBs.
 */
SET IMPLICIT_TRANSACTIONS OFF; WHILE 1 < @@TRANCOUNT ROLLBACK;
GO
DECLARE
  @dbname		SYSNAME,
  @tsql_command NVARCHAR(MAX);
DECLARE list CURSOR LOCAL FAST_FORWARD FOR
	SELECT tsql_command = REPLACE(N'USE [?]; PRINT @dbname;', '?', [name]), [name]
	  FROM sys.databases WHERE [state] = 0 AND 4 < database_id ORDER BY database_id DESC;
OPEN list;
WHILE 1=1 BEGIN;
  FETCH NEXT FROM list INTO @tsql_command, @dbname;
  IF @@FETCH_STATUS = 0 EXECUTE sp_executesql @tsql_command, N'@dbname SYSNAME', @dbname= @dbname; ELSE BREAK;
END;
CLOSE list;
DEALLOCATE list;